package com.hx.mypetstore.ui.order;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hx.mypetstore.Bean.OrderBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.common.ICallBack;
import com.hx.mypetstore.constant.OrderState;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.util.SPUtil;
import com.hx.mypetstore.util.view.AssessDialog;
import com.hx.mypetstore.util.view.CancelDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderActivity extends AppCompatActivity implements OrderAdapter.CheckInterface , View.OnClickListener{

    /**
     * 订单list
     */
    private ListView mListView;

    /**
     * 适配器
     */
    private OrderAdapter mAdapter;

    /**
     * 待付款
     */
    private ImageView im_dfk;

    /**
     * 待发货
     */
    private ImageView im_dfh;

    /**
     * 待收货
     */
    private ImageView im_dsh;

    /**
     * 待评价
     */
    private ImageView im_dpj;

    /**
     * 放回按钮
     */
    private ImageView back;


    /**
     * 是否有评价
     */
    private boolean assessKey = false;
    private Context mContext;
    private List<OrderBean> orderList;
    private String TAG = "订单页";
    private OrderAdapter orderAdapter;


    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //定义一个弹出层dialog
            AlertDialog alert = new AlertDialog.Builder(mContext).create();

            switch (msg.what) {
                case -6:
                    Toast.makeText(mContext, "你已经评价过此订单", Toast.LENGTH_SHORT).show();
                    break;
                case -5:
                    Toast.makeText(mContext, "评价成功", Toast.LENGTH_SHORT).show();
                    break;
                case -4:
                    Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT).show();
                    break;
                case -3:
                    Toast.makeText(mContext, "申请成功", Toast.LENGTH_SHORT).show();
                    break;
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求处理失败！获取商品数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //网络请求订单信息数据成功
                    orderList = SPUtil.getDataList(mContext,SPConstants.ORDER_LISt,OrderBean.class);
                    orderAdapter = new OrderAdapter(mContext,orderList);
                    orderAdapter.setCheckInterface(OrderActivity.this);
                    mListView.setAdapter(orderAdapter);
                    break;
                case 5:
                    Toast.makeText(mContext, "确认成功", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(mContext, "余额不足", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(mContext, "购买成功", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(mContext, "取消成功", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        mContext = getApplicationContext();
        //请求数据
        initData(OrderState.NOAPPLY);
        //初始化绑定组件
        init();
    }

    private void initData(Integer state) {
        String url = HttpURL.GETORDERBYSTATE;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .add("state",state.toString())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "订单数据"+jsonObject.toString());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        message.what = 1;
                        String order = jsonObject.getString("data");
                        //Json 解析对象
                        JsonParser jsonParser = new JsonParser();
                        JsonArray jsonArray = jsonParser.parse(order).getAsJsonArray();
                        //JsonArray jsonArray = jsonObject1.getAsJsonArray("msg");
                        Gson gson = new Gson();
                        ArrayList<OrderBean> list = new ArrayList<>();
                        for (JsonElement add : jsonArray) {
                            OrderBean Bean = gson.fromJson(add, OrderBean.class);
                            list.add(Bean);
                        }
                        Log.e(TAG, "list"+list);
                        SPUtil.saveDataList(mContext,SPConstants.ORDER_LISt,list);
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void init() {
        mListView = findViewById(R.id.list_order);
        im_dfk = findViewById(R.id.order_zf);
        im_dfh = findViewById(R.id.order_fh);
        im_dsh = findViewById(R.id.order_sh);
        im_dpj = findViewById(R.id.order_pj);
        back = findViewById(R.id.title_back);

        back.setOnClickListener(this);
        im_dfk.setOnClickListener(this);
        im_dpj.setOnClickListener(this);
        im_dfh.setOnClickListener(this);
        im_dsh.setOnClickListener(this);
    }

    @Override
    public void checkGroup(int position) {
        OrderBean orderBean = orderList.get(position);
        apply(orderBean);
        initData(OrderState.UNDELIVERED);
    }

    @Override
    public void checkGroup1(int position) {
        OrderBean orderBean = orderList.get(position);
        cancel(orderBean);
        initData(OrderState.UNDELIVERED);
    }


    @Override
    public void checkGroup2(int position) {
        OrderBean orderBean = orderList.get(position);
        comfirm(orderBean);
        initData(OrderState.FINISH);
    }


    @Override
    public void checkGroup3(int position) {
        Log.e(TAG, "评价" );
        OrderBean orderBean = orderList.get(position);

        haveAssess(orderBean);
        if (!assessKey) {
            Assess(orderBean);
        }
        initData(OrderState.FINISH);
    }


    @Override
    public void checkGroup4(int position) {
        Log.e(TAG, "checkGroup4: success" );
        OrderBean orderBean = orderList.get(position);
        finishReason(orderBean);
        //applyCancel(orderBean);
        initData(OrderState.FINISH);
    }

    //评价  -- 对话框
    private void Assess(OrderBean orderBean) {
        // 显示填写理由
        FragmentManager manager = getSupportFragmentManager();
        DialogFragment fragment = (DialogFragment) manager.findFragmentByTag("mAssessDialog");
        if ((fragment != null) && (fragment.getDialog() != null) && (fragment.getDialog().isShowing())) {
            return;
        }
        AssessDialog mAssessDialog = AssessDialog.newInstance();
        mAssessDialog.setCallBack(new ICallBack<String>() {
            @Override
            public void onSuccess(String bean) {
                Log.e(TAG, "确认 退单：：：： "+bean );
                assessRequest(orderBean,bean);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
        mAssessDialog.show(getSupportFragmentManager(), "mAssessDialog");
    }

    //该商品是否评价过
    private void haveAssess(OrderBean orderBean) {
        String url = HttpURL.HAVEASSESS;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("orderid",orderBean.getId())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Log.e(TAG, "是否有过评价" + jsonObject);
                    if (jsonObject.getBoolean("success")) {
                        assessKey = true;
                        Message message = Message.obtain();
                        message.what = -6;
                        uiHandler.sendMessage(message);
                    }else{
                        assessKey = false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //评价请求
    private void assessRequest(OrderBean orderBean, String bean) {
        String url = HttpURL.ASSESS;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("goodid",orderBean.getGoodid().toString())
                .add("orderid",orderBean.getId())
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .add("assess",bean)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    message.what = -5;
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //退款理由 -- 对话框
    private void finishReason(OrderBean orderBean ) {
        // 显示填写理由
        FragmentManager manager = getSupportFragmentManager();
        DialogFragment fragment = (DialogFragment) manager.findFragmentByTag("mCancelDialog");
        if ((fragment != null) && (fragment.getDialog() != null) && (fragment.getDialog().isShowing())) {
            return;
        }
        CancelDialog mCancelDialog = CancelDialog.newInstance();
        mCancelDialog.setCallBack(new ICallBack<String>() {
            @Override
            public void onSuccess(String bean) {
                Log.e(TAG, "确认 退单：：：： "+bean );
                applyCancel(orderBean,bean);
            }

            @Override
            public void onError(String errorMsg) {
            }
        });
        mCancelDialog.show(getSupportFragmentManager(), "mCancelDialog");
    }
    private void applyCancel(OrderBean orderBean,String reason) {
        String url = HttpURL.APPLYCANCEL;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("id",orderBean.getId())
                .add("reason",reason)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    message.what = -3;
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void apply(OrderBean orderBean) {
        String url = HttpURL.BUY;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", (String) SPUtil.get(mContext, SPConstants.KEY_LOCAL_USER,""))
                .add("id",orderBean.getId())
                .add("price",orderBean.getPrice())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 3;
                    else{
                        message.what = 4;
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void cancel(OrderBean orderBean) {
        String url = HttpURL.CANCEL;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("id",orderBean.getId())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    message.what = -4;
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void comfirm(OrderBean orderBean) {
        String url = HttpURL.CONFIRM;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("id",orderBean.getId())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    message.what = 5;
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }



    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.title_back:
                finish();
                break;
            case R.id.order_zf:
                initData(OrderState.NOAPPLY);
                break;
            case R.id.order_fh:
                initData(OrderState.UNDELIVERED);
                break;
            case R.id.order_sh:
                initData(OrderState.INDELIVERED);
                break;
            case R.id.order_pj:
                initData(OrderState.FINISH);
                break;
        }
    }
}